package com.ita.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ita.entity.User;
import com.ita.service.IUserService;
import com.ita.service.impl.UserServiceImpl;
import com.ita.validator.IValidator;
import com.ita.validator.impl.UserNameValidator;

/**
 * Servlet implementation class AddUserServlet
 */
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IUserService service=new UserServiceImpl();    
	private IValidator nv=new UserNameValidator();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		addUser(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		addUser(request,response);
	}
	private void addUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		
		String userId = null;
		String userName = null;
		String password = null;
		String address = null;
		File f = null;
		boolean isMultipart=ServletFileUpload.isMultipartContent(request);
		if(isMultipart){
			DiskFileItemFactory factory=new DiskFileItemFactory();
			factory.setSizeThreshold(2*1024);
			ServletFileUpload upload=new ServletFileUpload(factory);
			
			try {
				List<FileItem> list=upload.parseRequest(request);
				
				Iterator<FileItem > i=list.iterator();
				while(i.hasNext()){
					FileItem item=i.next();
					if(item.isFormField()){//是一个表单域
//						System.out.println(item.getFieldName()+"..."+item.getString("utf-8"));
						if("userId".equals(item.getFieldName())){
							userId=item.getString("utf-8");
						}
						if("userName".equals(item.getFieldName())){
							userName=item.getString("utf-8");
						}
						if("password".equals(item.getFieldName())){
							password=item.getString("utf-8");
						}
						if("address".equals(item.getFieldName())){
							address=item.getString("utf-8");
						}
					}
					else{
						String fileName=item.getFieldName();
						System.out.println("file size:"+item.getSize());
						
						upload.setFileSizeMax(10*1024*1024);//上传文件的限制，为10m
						f=new File("d:/pic/"+UUID.randomUUID()+fileName);
						try {
							item.write(f);
							
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
				
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			
		}
		List<String> errMsg=new ArrayList<String>();
		List<String> ll=nv.validate(userName);
		errMsg.addAll(ll);
		String userPic=f.getAbsolutePath();
		
		System.out.println(userPic);
		if(errMsg.size()==0){
		
			User user=new User(userId, userName,password, address,userPic);
			System.out.println(user.toString());
			if(service.insertUser(user)){
				request.getRequestDispatcher("login.html").forward(request, response);
			}
			else{
				request.getRequestDispatcher("addUser.jsp").forward(request, response);
			}
			
		}
		else{
			request.setAttribute("errMsg", errMsg);
			request.getRequestDispatcher("addUser.jsp").forward(request, response);
		}
		
		
	}
	
}
